<script setup>
import {ref} from 'vue';
import {getMemberDetailApi, addFollowApi, getFollowListApi, updateCategoryApi} from '@/service/member.js';
import {getStatusPickerApi} from '@/service/setting';
import {getCategoryListApi} from '@/service/goods.js';
import ProductEdit from "./product-edit.vue";
import ZoneEdit from "./zone-edit.vue";
import {ElMessage} from 'element-plus';

const emit = defineEmits(['reload']);
const reload = () => {
  emit('reload');
};

// 获取跟进状态
const statusLit = ref([]);
const fetchStatusList = () => {
  getStatusPickerApi().then(({code, data}) => {
    if (code === 200) {
      statusLit.value = data;
    }
  });
};

// 获取分类
const categoryList = ref([]);
const fetchCategoryList = () => {
  getCategoryListApi().then(res => {
    if (res.code === 200) {
      categoryList.value = res.data.list;
    }
  });
};

// 跟进表单
const visitForm = ref({
  member_id: '',
  status: '',
  remark: '',
  next_visit_time: '',
  files: []
});

// 跟进表单验证规则
const rules = ref({
  status: [
    {required: true, message: '请选择跟进状态', trigger: 'change'}
  ],
  remark: [
    {required: true, message: '请输入跟进记录', trigger: 'blur'}
  ]
});

// init visit form
const initVisitForm = () => {
  visitForm.value = {
    member_id: '',
    status: '',
    remark: '',
    next_visit_time: '',
    files: []
  };
};

// 分配信息
const allocate = ref({
  id: '',
  member_id: '',
  from_user: {
    id: '',
    realname: ''
  },
  user: {
    id: '',
    realname: ''
  },
  create_time: '',
});

// 客资详情
const customer = reactive({
  id: "",
  category: {
    id: "",
    title: ''
  },
  source: {
    id: "",
    title: ''
  },
  city: {
    id: "",
    name: '',
    shortname: ''
  },
  creator: {
    id: "",
    realname: ''
  },
  create_time: '',
  zone: []
});

// 定义联系人
const contacts = ref([]);

// 咨询的产品
const product = ref({
  id: '',
  event_date: '',
  budget: '',
  table_amount: '',
});

// 跟进记录
const visits = ref([]);
// 获取跟进记录
const fetchFollowList = (member_id) => {
  getFollowListApi({member_id}).then(({code, data}) => {
    if (code === 200) {
      visits.value = data;
    }
  });
};

// 打开抽屉
const visible = ref(false);
const openDrawer = (row) => {
  visible.value = true;
  initVisitForm();
  getMemberDetailApi(row).then(({code, data, msg}) => {
    contacts.value = data.contacts;
    Object.assign(customer, data.customer);
    product.value = data.product;
    visits.value = data.visits;
    allocate.value = data.allocate;
  });
};

// 关闭抽屉
const closeDrawer = () => {
  visible.value = false;
};

// 处理tab点击事件
const handleTabClick = (tab) => {
  // console.log(tab);
};

const activeName = ref('first');

// 添加回访记录
const handleFollow = () => {
  let member_id = customer.id;
  visitForm.value.member_id = member_id;
  addFollowApi(visitForm.value).then(({code, msg}) => {
    if (code === 200) {
      ElMessage.success(msg);
      reload();
      fetchFollowList(member_id);
      initVisitForm();
    } else {
      ElMessage.error(msg);
    }
  });
};

// 显示产品编辑弹窗
const productEditRef = ref(null);
const showProductEdit = () => {
  productEditRef.value.openDialog(product.value);
};

// 显示区域编辑弹窗
const zoneEditRef = ref(null);
const showUpdateZone = () => {
  zoneEditRef.value.openDialog(customer);
};

const selectedCategoryId = ref('');
const categoryPopVisible = ref(false);
const showCategoryPop = () => {
  selectedCategoryId.value = customer.category.id;
  categoryPopVisible.value = true;
};

const closeCategoryPop = () => {
  categoryPopVisible.value = false;
};

const confirmChangeCategory = () => {
  categoryPopVisible.value = false;
  if (!selectedCategoryId.value) {
    ElMessage.warning('请选择分类');
    return;
  }

  if (selectedCategoryId.value == customer.category.id) {
    ElMessage.warning('请选择不同分类');
    return;
  }

  customer.category.id = selectedCategoryId.value;
  // 查找对应得分分类
  let selectCategory = categoryList.value.find(item => item.id == selectedCategoryId.value);
  if (selectCategory) customer.category.title = selectCategory.title;

  // 更新分类
  updateCategoryApi({id: customer.id, category_id: selectedCategoryId.value}).then(res => {
    if (res.code === 200) {
      ElMessage.success(res.msg);
      reload();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 编辑联系人
import ContactEdit from "./contact-edit.vue";
const contactEditRef = ref(null);
const showEditContact = (row) => {
  contactEditRef.value.openDialog(row);
};

// 追加联系人
import ContactAppend from "./contact-append.vue";
const contactAppendRef = ref(null);
const showAppendContact = () => {
  contactAppendRef.value.openDialog(customer.id);
};

const handleUpdateContacts = (updatedContacts) => {
  contacts.value = updatedContacts;
};

defineExpose({
  openDrawer
});


onMounted(() => {
  fetchStatusList();
  fetchCategoryList();
});
</script>

<template>
  <el-drawer v-model="visible" title="客资详情" :with-header="false" size="500px" direction="rtl"
             body-class="drawer-detail" :before-close="closeDrawer">
    <div class="drawer-header">
      <el-row class="customer-head">
        <el-col :span="12">
          <div class="avatar-box">
            <el-avatar shape="square" size="large"
                       src="https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png"/>
            <div class="right">
              <el-popover :visible="categoryPopVisible" placement="bottom">
                <template #reference>
                  <h3 @click="showCategoryPop">{{ customer.category.title ? customer.category.title : '其他' }}</h3>
                </template>
                <div>
                  <div class="form-box" style="margin-bottom: 5px;">
                    <el-select v-model="selectedCategoryId" placeholder="请选择客资分类" style="width: 100%"
                               @click.stop>
                      <el-option v-for="item in categoryList" :key="item.id" :label="item.title" :value="item.id+''"/>
                    </el-select>
                  </div>
                  <div class="btn-group">
                    <el-button size="small" @click="closeCategoryPop">取消</el-button>
                    <el-button type="primary" @click="confirmChangeCategory">确定</el-button>
                  </div>
                </div>
              </el-popover>
              <p>{{ customer.source.title }}</p>
            </div>
          </div>
        </el-col>
        <el-col :span="12"></el-col>
      </el-row>
      <el-descriptions :column="3" direction="vertical" border>
        <el-descriptions-item label="城市">{{ customer.city.name }}</el-descriptions-item>
        <el-descriptions-item label="区域" :span="2">
          <template #label>
            <div class="btn-label">
              <span>区域</span>
              <el-button class="btn-product" icon="Edit" type="primary" @click="showProductEdit"></el-button>
            </div>
          </template>
          <el-tag style="margin-right: 3px;" v-for="item in customer.zone" :key="item" type="primary">{{ item.name }}
          </el-tag>
          <el-tag type="danger" style="cursor: pointer;" @click="showUpdateZone">+</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="婚期">{{ product.event_date ? product.event_date : '-' }}</el-descriptions-item>
        <el-descriptions-item label="预算">{{ product.budget ? product.budget : '-' }}</el-descriptions-item>
        <el-descriptions-item label="桌数">{{
            product.table_amount ? product.table_amount : '-'
          }}
        </el-descriptions-item>
      </el-descriptions>

      <el-table :data="contacts" border class="table-contacts">
        <el-table-column prop="role_type" label="角色" width="50" align="center">
          <template #default="{row}">
            <el-link type="primary" @click="showEditContact(row)">{{ row.role_type}}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="称呼" width="100" align="center"></el-table-column>
        <el-table-column prop="contact" label="联系方式">
          <template #header>
            <div class="contacts-table-header">
              <span>联系方式</span>
              <el-icon size="16" color="#409EFF" @click="showAppendContact"><CirclePlus /></el-icon>
            </div>
          </template>

          <template #default="{row}">
            <div class="contact">
              <el-icon class="icon" v-if="row.type == 1">
                <Iphone/>
              </el-icon>
              <el-icon class="icon" v-else>
                <ChatLineRound/>
              </el-icon>
              <el-link type="primary" :href="'tel:' + row.contact">{{ row.contact }}</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-tabs v-model="activeName" @tab-click="handleTabClick" type="border-card" style="margin: 0 1rem;">
      <el-tab-pane label="跟进" name="first">
        <el-form v-model="visitForm" :rules="rules" label-position="top">
          <el-form-item label="跟进记录">
            <el-input v-model="visitForm.remark" type="textarea" :rows="3" placeholder="请输入内容"/>
          </el-form-item>
          <el-form-item>
            <el-row :gutter="10" style="width: 100%">
              <el-col :span="8">
                <el-select v-model="visitForm.status" clearable placeholder="请选择跟进状态">
                  <el-option v-for="item in statusLit" :key="item.id" :label="item.title" :value="item.id"/>
                </el-select>
              </el-col>
              <el-col :span="8">
                <el-date-picker v-model="visitForm.next_visit_time" type="date" value-format="YYYY-MM-DD"
                                placeholder="下次回访时间" style="max-width:160px;"/>
              </el-col>
              <el-col :span="8" style="text-align: right;">
                <el-button type="primary" @click="handleFollow">保存</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
        <el-divider></el-divider>
        <el-timeline style="max-width: 600px">
          <el-timeline-item v-for="item in visits" :key="item.id" :timestamp="item.create_time" placement="top">
            <el-descriptions :column="1">
              <el-descriptions-item label="跟进状态">
                <el-tag type="primary">{{ item.status_title }}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="跟进人">{{ item.user.realname }}</el-descriptions-item>
              <el-descriptions-item label="下次跟进时间">{{ item.next_visit_time }}</el-descriptions-item>
              <el-descriptions-item label="跟进记录">{{ item.remark }}</el-descriptions-item>
            </el-descriptions>
          </el-timeline-item>
        </el-timeline>
      </el-tab-pane>
      <el-tab-pane label="其他信息" name="second">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="创建人">{{ customer.creator.realname }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ customer.create_time }}</el-descriptions-item>
          <el-descriptions-item label="跟进人">{{ allocate.user.realname }}</el-descriptions-item>
          <el-descriptions-item label="分配时间">{{ allocate.create_time }}</el-descriptions-item>
          <el-descriptions-item label="备注">{{ customer.remark }}</el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
    </el-tabs>

    <el-button type="danger" circle icon="Close" @click="closeDrawer"
               style="position: absolute; top: 1rem; right: 1rem"/>

    <ProductEdit ref="productEditRef"/>
    <ZoneEdit ref="zoneEditRef"/>
    <ContactEdit ref="contactEditRef"/>
    <ContactAppend ref="contactAppendRef" @update:contacts="handleUpdateContacts"/>
  </el-drawer>
</template>

<style scoped lang="less">
.drawer-header {
  background-color: #EBEDF0;
  padding: 1rem;

  .customer-head {
    margin-bottom: 10px;


    .avatar-box {
      display: flex;
      align-items: center;

      .right {
        margin-left: 10px;

        h3 {
          color: #E6A23C;
          font-size: 18px;
          margin-bottom: 5px;
          text-decoration: underline 1px;
          text-underline-offset: 5px;
          cursor: pointer;
        }

        p {
          font-size: 14px;
          color: #606266;
        }
      }
    }

    .tag-zone {
      margin-right: 5px;
    }
  }

  .table-contacts {
    margin-top: 1rem;

    .contacts-table-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
    }
  }


  .contact {
    display: flex;
    align-items: center;
    color: #409EFF;

    .icon {
      margin-right: 3px;
    }
  }
}
</style>
